const express = require('express');
const router = express.Router();
const path = require('path');
const formidable = require('formidable');
const fs = require('fs');
const OSS = require('ali-oss').Wrapper;
const config = require('../config'); //获取配置文件信息
//oss设置
const options = {
    region: config.region,
    accessKeyId: config.accessKeyId,
    accessKeySecret: config.accessKeySecret,
    bucket: config.bucket
};
const client = new OSS(options);
client.putBucketCORS(config.bucket, config.region, [
    {
        allowedOrigin: '*',
        allowedMethod: ['GET', 'POST', 'HEAD', 'PUT', 'DELETE'],
        allowedHeader: ['Content-Type', 'Content-Length', 'Authorization', 'Accept', 'X-Requested-With'],
    }
]);
//图片缓存文件夹
const uploadFilePath = path.join(__dirname, '../uploadFile');
router.post('/img', (req, res) => {
    if (!fs.existsSync(uploadFilePath)) {
        fs.mkdirSync(uploadFilePath);
    };
    const form = new formidable.IncomingForm({
        uploadDir: uploadFilePath,
        maxFieldsSize: 2 * 1024 * 1024
    });
    form.parse(req, (err, fields, files) => {
        if (err) {
            return res.json({
                code: 201,
                mes: '发生错误!'
            })
        }
        if (!files.img || !files.img.path) {
            return res.json({
                code: 201,
                mes: '缺少参数'
            })
        }
        if (!/(.*)(\.jpg|\.png|\.gif|\.jpeg)$/.test(files.img.name)) {
            fs.unlink(files.img.path, () => { });
            return res.json({
                code: 201,
                mes: '不支持的图片格式'
            })
        }
        const stream = fs.createReadStream(files.img.path);
        const path = 'uploadimg/' + files.img.name.replace(/(.*)(\.jpg|\.png|\.gif|\.jpeg)$/, `${Date.now()}_${Math.floor(Math.random() * 9)}$2`);
        return client.putStream(path, stream).then(result => {
            fs.unlink(files.img.path, () => { });
            return res.json({
                code: 200,
                data: result.url
            })
        }).catch(err => {
            return res.json({
                code: 201,
                mes: '发生错误!',
                conten: err
            })
        })
    });
})

module.exports = router
